<template>
<div>
    <div class="index" id="play" v-if="!verticalScreen">
        <div id="web_bg" :style="webBg"></div>
        <div class="m-close" v-if="isAppEnv" @click="closePage">
            <img src="./../assets/close3.png">
        </div>
        <div class="head clear">
            <div class="img fl" v-show="isLogined">
                <img :src="userAvatar">
            </div>

            <div class="head-info fl">
                <!-- <span class="name" v-show="isLogined">{{ userName }}</span> -->
                <!-- <span class="name" v-show="!isLogined">请登录</span> -->
                <p class="title">{{(isLogined ? userName: "请登录") + "，欢迎进入" + liveTitle}}</p>
                <div>
                    <img v-show="liveInfo.liveMode == 1" src="../assets/audio.gif" alt="">
                    <h5>{{livePlayUv}}人气</h5>
                </div>
            </div>
        </div>

        <div class="m-video">
            <div class="countdown-mark" v-show="countdownShow" :class="{'z-top': showedTopViedo}">
                <div class="countdown">
                    <h5>…距开播还有…</h5>
                    <h4>{{countdownDay}}<span>天 </span>{{countdownHour}}<span>时 </span>{{countdownMinute}}<span>分 </span></h4>
                </div>
            </div>
            <!-- 移动端监听play()方法回调，但是视频并没有播放 -->
            <!-- <div class="audio" v-show="audioShow && liveInfo.liveMode == 1">
                <img src="../assets/audio.gif" alt="">
                <p>语音直播中</p>
                <img src="../assets/audio.gif" alt="">
            </div> -->
            <div class="play-error" v-show="palyErrorShow">
                <img src="https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-error-0.png" alt="">
            </div>
            <div :class="{'z-top': showedTopViedo && !needFakeFullScreen, 'z-full': needFakeFullScreen}"
                :style="needFakeFullScreen ? fullHeightStyle : {}"
                class="video"
                >

                <!-- 直播结束显示图 -->
                <img v-show="liveIsOver && isLogined" :src="videoBgImg" class="live-over-show">

                <!-- 播放器容器 -->
                <div class="prism-player"
                    ref="video"
                    id="player-con"
                    :style="[bgPic ? videoBg : '']"></div>

                <!-- 播放器控制组件 -->
                <div v-show="showedVideoControlBar && !isOverdueHiddenVideoControlBar" class="video-controller">
                    <!-- 全屏 -->
                    <div class="video-btn"
                        :class="{'z-on': videoIsFullScreen}"
                        @touchstart.stop.prevent="shiftFullVideo"
                        @click.stop.prevent>
                        <img src="./../assets/to-full-screen.png">
                        <img src="./../assets/to-small-screen.png">
                    </div>

                    <!-- 暂停/播放 -->
                    <!-- <div class="video-btn"
                        v-show="liveInfo.liveStatus == 3"
                        :class="{'z-on': videoIsPlaying}"
                        @touchstart.stop.prevent="shiftVideoPlay"
                        @click.stop.prevent>
                        <img src="./../assets/play.png">
                        <img src="./../assets/pause.png">
                    </div> -->

                    <!-- 分辨率按钮横屏 -->
                    <!-- <div 
                        class="gqbtn"
                        v-show="isCrosswise && liveInfo.liveStatus == 1"
                        @touchstart.stop.prevent="shiftQualityFullScreen"
                        @click.stop.prevent>
                        <img src="../assets/shipin-big.png" alt="">
                        <span>{{qualityValue}}</span>
                    </div> -->
                </div>

                <!-- 分辨率按钮竖屏 -->
                <!-- <div 
                    class="video-controller videoQuality" 
                    v-show="showedVideoControlBar && !isOverdueHiddenVideoControlBar && !quality && !isCrosswise && liveInfo.liveStatus == 1"
                    >
                    <div 
                        class="gqbtn"
                        @touchstart.stop.prevent="shiftQuality"
                        @click.stop.prevent>
                        <img src="../assets/shipin-big.png" alt="">
                        <span>{{qualityValue}}</span>
                    </div>
                </div> -->

                <!-- 分辨率竖屏选择 -->
                <!-- <div class="chooseQuality video-controller slideInRight" v-show="quality && !isCrosswise">
                    <div class="SD">
                        <div class="huazhi"
                            @touchstart.stop.prevent="quality = false;" 
                            @click.stop.prevent>
                            <img src="../assets/shipin-small.png" alt="">
                            <span>画质</span>
                        </div>
                        <ul class="quality">
                            <li 
                            
                                :class="{'active':thisQuality == 1}" 
                                @touchstart.stop.prevent="changeQuality(1)"
                                @click.stop.prevent>
                                <p>1080P</p>
                                <p>高清</p>
                            </li>
                            <li 
                                :class="{'active':thisQuality == 2}"
                                @touchstart.stop.prevent="changeQuality(2)"
                                @click.stop.prevent>
                                <p>720P</p>
                                <p>标清</p>
                            </li>
                            <li 
                                :class="{'active':thisQuality == 3}"
                                @touchstart.stop.prevent="changeQuality(3)"
                                @click.stop.prevent>
                                <p>480P</p>
                                <p>流畅</p>
                            </li>
                        </ul>
                    </div>
                </div> -->
                <!-- 分辨率横屏选择 -->
                <div class="SDFullScreen" v-show="qualityFullScreen && isCrosswise">
                    <div class="huazhi" @touchstart.stop.prevent="qualityFullScreen=false" @click.stop.prevent>
                        <img src="../assets/shipin-small.png" alt="">
                        <span>画质</span>
                    </div>
                    <ul class="quality">
                        <li 
                            :class="{'active':thisQuality == 1}" 
                            @touchstart.stop.prevent="changeQuality(1)"
                            @click.stop.prevent>
                            <p>1080P</p>
                            <p>高清</p>
                        </li>
                        <li 
                            :class="{'active':thisQuality == 2}"
                            @touchstart.stop.prevent="changeQuality(2)"
                            @click.stop.prevent>
                            <p>720P</p>
                            <p>标清</p>
                        </li>
                        <li 
                            :class="{'active':thisQuality == 3}"
                            @touchstart.stop.prevent="changeQuality(3)"
                            @click.stop.prevent>
                            <p>480P</p>
                            <p>流畅</p>
                        </li>
                    </ul>
                </div>


                <!-- 关闭页面 -->
                <div class="close-btn"
                    @touchstart.stop.prevent="closePage"
                    v-if="isAppEnv"
                    v-show="showedTopViedo &&  !needFakeFullScreen">
                    <img src="./../assets/close2.png">
                </div>
            </div>
        </div>

        <!-- 侧边悬浮按钮：我要直播 -->
        <div class="TVBox" :class="{'out': showedTVBox}">
            <div :class="{'z-dim': false}">
                <!-- <img @click="showedTVBox = false" src="./../assets/close.png" class="i-close"> -->
                <img @click="showTvbox" src="./../assets/watchTV.png" class="tv-img animated swing">
            </div>
        </div>

        <!-- 我要直播模块 -->
        <div class="TVintroduce a-fade-in" @click.self="clickTVBOx = !clickTVBOx;showedTVBox = false;" v-show="clickTVBOx">
            <div class="introduce">
                <!-- <img class="" src="../assets/introduce_bg.png" alt="">
                <div>
                    <img src="../assets/introduce_name.png" alt="">
                </div> -->
                <img class="introduce-bg" src="../assets/introduce_bg.png" alt="">
                <img class="introduce-title" src="../assets/introduce_title.png" alt="">
                <a href="tel:18806481128">
                    <img src="../assets/introduce.png" alt="">
                </a>
            </div>
        </div>

        <!-- 聊天/了解我 -->
        <div class="content" :class="{'z-top': showedTopViedo && !needFakeFullScreen}" v-show="!needFakeFullScreen">
            <div class="chat">
                <div class="nav" :class="{'z-3': isAppEnv}">
                    <ul>
                        <li :class="{'active':show}" @click="changeStyle(1)">大家说</li>
                        <li :class="{'active':!show}" @click="changeStyle(2)">了解我</li>
                        <li class="z-stress" @click="toShare" v-show="isAppEnv">
                            <img src="./../assets/share2.png">
                            分享
                        </li>
                    </ul>
                </div>

                <div class="chatWindow" v-show="show">
                    <div class="sys clear a-fade-in-right" v-show="showSysMessage">
                        <div class="system fl">
                            <span>&nbsp;系统消息：</span>
                            <span>{{message2}}</span>加入房间
                        </div>
                    </div>

                    <div class="show" id="shows"
                        :style="fullHeightStyle"
                        :class="{'unfold': openEmoji || openPhoto}"
                        ref="ol"
                        @click="openEmoji=false;openPhoto=false">
                        
                        <ul id="ul" ref="chatList" @click="openEmoji=false;openPhoto=false">
                            <template v-for="(item, index) in chatList">
                                <!-- 对方消息: 文字 -->
                                <li v-if="item.from_id != jmsgUser"
                                    class="clear"
                                    :key = "index">
                                    <!-- <div class="ava fl"><img :src="item.avatar"></div> -->
                                    <div class="label fl">
                                        <div class="name s-office">
                                            {{item.from_name}}
                                        </div>
                                        <div class="cont left">
                                            <p class="message" style="word-break:break-all;" v-html="item.msg_body.text"></p>
                                        </div>
                                    </div>
                                </li>
                                <!-- 官方消息 -->
                                <!-- <li v-if="(item.from_id==1)"
                                    class="clear"
                                    :key = "index">
                                    <div class="label fl">
                                        <div class="name s-office">
                                            {{item.from_name}}
                                            <span>官方</span>
                                        </div>
                                        <div class="cont left">
                                            <p class="message" style="word-break:break-all;" v-text="item.msg_body.text"></p>
                                        </div>
                                    </div>
                                </li> -->


                                <!-- 自已发送消息: 文字 -->
                                <li class="self"
                                    :key = "index"
                                    v-if="item.from_id == jmsgUser">
                                    <div class="label">
                                        <div class="name s-office" style="text-align: right;">
                                            {{ item.from_name }}
                                        </div>
                                        <div class="cont right">
                                            <p class="message" style="word-break:break-all;" v-html="item.msg_body.text"></p>
                                        </div>
                                    </div>
                                </li>
                            </template>
                        </ul>
                    </div>
                </div>

                <div class="aboutMe" v-show="!show" ref="adoutMeRef">
                    <div class="m-info">
                        <div class="box1">
                            <img src="./../assets/goose-video.png">
                        </div>
                        <p class="h2">{{liveTitle}}</p>
                        <ul class="ul1">
                            <li :style="li1">
                                <p>活动时间：{{getTimeStr(liveInfo.liveBeginTime)}}</p>
                            </li>
                            <li :style="li3">
                                <p>主办方/主讲人：{{liveInfo.liveLecturer || "无"}}</p>
                            </li>
                        </ul>
                        <p class="h2-special">直播简介</p>
                        <p class="h5">精彩直播 周周不断</p>
                        <div class="activeBox"
                            ref="activ">
                            <div class="detail">
                                <img :src="liveInfo.liveImg">
                                <p>{{liveInfo.liveDescription || "&emsp;&emsp;【" + liveTitle + "】由“大鹅视频”直播平台全程提供直播服务支持。手机端一键轻松创建直播，培训、网课、会议等场景全覆盖，直播内容云端永久存储，一键下载，更有密码、红包、答题、抽奖、签到等功能助力线上直播营销。"}}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部占位符，用于页面滚动标记 -->
        <div class="u-bottom-tag" ref="pageBottomTag"></div>

        <!-- 聊天输入 -->
        <div class="m-fm" ref="chatInputView" v-show="show && !needFakeFullScreen">
            <div class="shade" v-show="!isLogined" @click="checkLogin"></div>
            
            <div class="send clear" :class="{'z-focus': cont!=''}">
                <div class="text fl" style="backgroundImage:'url(' + require('../assets/talk.png') + ')'">
                    <input
                        type="text"
                        id="inputId"
                        v-model="cont"
                        class="fl"
                        placeholder="快来吐槽呗～"
                        @keyup.enter="sendChatroomMsg"
                        @blur="handleInputBlur"
                        @focus="handleInputFocus">
                </div>
                <div @click="sendChatroomMsg" @touchstart="sendChatroomMsg" class="btn fr a-scale-in">发送</div>
            </div>

            <div class="pic" v-show="openPhoto">
                <img
                    src="./../assets/pic.png"
                    class="upload-pic"
                    @click="startUploadImg" >
                <span>图片</span>
                <input type="file" accept="image/*" name="asd" id="file" @change="uploadImg">
            </div>
        </div>
        <!-- 密码弹窗 -->
        <div class="dialog-mark" v-show="showPassword && (liveType == 1)" ref="dialogPassword">
            <div class="dialog">
                <div class="form__cover"></div>
                <div class="form__content">
                    <!-- 密码 -->
                    <div class="styled-input" v-show="liveType == 1">
                        <input 
                            autocomplete="off"
                            type="password" 
                            class="styled-input__input" 
                            placeholder="直播密码"
                            maxLength="4"
                            v-model="password">
                        <div class="styled-input__circle"></div>
                    </div>
                    <button type="button" class="styled-button" @click="submitPassword" >
                        <span class="styled-button__text">观看</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="index" id="play2" v-if="verticalScreen">
        <div class="m-fm" ref="chatInputView" :class="{'small':!chatInputIsFocused}">
            <div class="send clear" :class="{'z-focus': cont!=''}">
                <input
                        type="text"
                        id="inputId"
                        v-model="cont"
                        class="fl"
                        placeholder="说点什么..."
                        @keyup.enter="sendChatroomMsg"
                        @blur="handleInputBlur"
                        @focus="handleInputFocus">
                <div @touchstart="sendChatroomMsg" class="btn fr a-scale-in">发送</div>
            </div>
        </div>
        <div class="touch-mark clear" id="touch-mark">
            <div class="touch-left" id="touch-left" @touchstart.stop="touchStart($event, 1)" @touchmove.stop="touchMove($event, 1)" @touchend.stop="touchEnd($event, 1)">
                <div class="chat-mark">
                    
                    <!-- <div class="m-fm small" @click="inputFocus()">
                        {{cont =="" ? "说点什么" : cont}}
                    </div> -->
                    <!-- <input class="m-fm small" type="text" v-show = "!chatInputIsFocused" v-model="cont" @click="inputFocus()" @touchstart="inputFocus()"> -->
                    
                </div>
                <div class="m-close" v-if="isAppEnv" @click="closePage">
                    <img src="./../assets/close3.png">
                </div>
                <div class="head clear z-top vertical-head">
                    <div class="img fl" v-show="isLogined">
                        <img :src="userAvatar">
                    </div>

                    <div class="head-info fl">
                        <p class="title">{{(isLogined ? userName: "请登录") + "，欢迎进入" + liveTitle}}</p>
                        <div>
                            <img v-show="liveInfo.liveMode == 1" src="../assets/audio.gif" alt="">
                            <h5>{{livePlayUv}}人气</h5>
                        </div>
                    </div>
                </div>
                <!-- 聊天/了解我 -->
                <div class="content" v-show="!needFakeFullScreen">
                    <div class="chat">
                        <div class="chatWindow">
                            <div class="weclome-box">
                                <div class="weclome" v-show="showSysMessage">
                                    {{message2}}进入直播间
                                </div>
                            </div>

                            <div class="show" id="shows"
                                ref="ol">
                                <ul id="ul" ref="chatList">
                                    <li v-for="(item, index) in chatList" :key="index">
                                        <div class="sys-msg" v-if="item.from_id == 1">
                                            <span>{{item.from_name}}：</span>{{item.msg_body.text}}
                                        </div>
                                        <div v-else>
                                            <span>{{item.from_name}}：</span>{{item.msg_body.text}}
                                        </div>
                                        <br/>
                                    </li>
                                    <!-- 防止内容过少inline-block不换行 -->
                                </ul>
                            </div>
                            <!-- <input type="text" v-model="cont" placeholder="说点什么..." @keyup.enter="sendChatroomMsg" @focus="chatShow = true;" v-show="!chatShow" /> -->
                        </div>
                    </div>
                </div>
                <div class="show-about" @click="verticaAboutShow = true">
                    <img src="./../assets/aboutMe.png" />
                </div>
            </div>
            <div class="touch-right" id="touch-right" @touchstart.stop="touchStart($event, 2)" @touchmove.stop="touchMove($event, 2)" @touchend.stop="touchEnd($event, 2)">

            </div>
        </div>
        <div class="m-video vertical">
            <div class="countdown-mark" v-show="countdownShow">
                <div class="countdown">
                    <h5>…距开播还有…</h5>
                    <h4>{{countdownDay}}<span>天 </span>{{countdownHour}}<span>时 </span>{{countdownMinute}}<span>分 </span></h4>
                </div>
            </div>
            <!-- <div class="audio" v-show="!audioShow && liveInfo.liveMode == 1">
                <img src="../assets/audio.gif" alt="">
                <p>语音直播中</p>
                <img src="../assets/audio.gif" alt="">
            </div> -->
            <div class="play-error" v-show="palyErrorShow">
                <img src="https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-error-1.png" alt="">
            </div>
            <div :class="{'z-top': showedTopViedo && !needFakeFullScreen, 'z-full': needFakeFullScreen}"
                :style="needFakeFullScreen ? fullHeightStyle : {}"
                class="video"
                >

                <!-- 直播结束显示图 -->
                <img v-show="liveIsOver && isLogined" :src="videoBgImg" class="live-over-show">

                <!-- 播放器容器 -->
                <div class="prism-player"
                    ref="video"
                    id="player-con"
                    :style="[bgPic ? videoBg : '']"></div>

                <!-- 关闭页面 -->
                <div class="close-btn"
                    @touchstart.stop.prevent="closePage"
                    v-if="isAppEnv"
                    v-show="showedTopViedo &&  !needFakeFullScreen">
                    <img src="./../assets/close2.png">
                </div>
            </div>
        </div>

        <div class="about-mark" :class="{show: verticaAboutShow}" @click.prevent="verticaAboutShow = false">
            <div class="aboutMe" ref="adoutMeRef">
                <div class="about-tag"></div>
                <div class="m-info">
                    <div class="box1">
                        <img src="./../assets/goose-video.png">
                    </div>
                    <p class="h2">{{liveTitle}}</p>
                    <ul class="ul1">
                        <li :style="li1">
                            <p>活动时间：{{getTimeStr(liveInfo.liveBeginTime)}}</p>
                        </li>
                        <li :style="li3">
                            <p>主办方/主讲人：{{liveInfo.liveLecturer || "无"}}</p>
                        </li>
                    </ul>
                    <p class="h2-special">直播简介</p>
                    <p class="h5">精彩直播 周周不断</p>
                    <div class="activeBox"
                        ref="activ">
                        <div class="detail">
                            <img :src="liveInfo.liveImg">
                            <p>{{liveInfo.liveDescription || "&emsp;&emsp;【" + liveTitle + "】由“大鹅视频”直播平台全程提供直播服务支持。手机端一键轻松创建直播，培训、网课、会议等场景全覆盖，直播内容云端永久存储，一键下载，更有密码、红包、答题、抽奖、签到等功能助力线上直播营销。"}}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 密码弹窗 -->
        <div class="dialog-mark" v-show="showPassword && (liveType == 1)" ref="dialogPassword">
            <div class="dialog">
                <div class="form__cover"></div>
                <div class="form__content">
                    <!-- 密码 -->
                    <div class="styled-input" v-show="liveType == 1">
                        <input 
                            autocomplete="off"
                            type="password" 
                            class="styled-input__input" 
                            placeholder="直播密码"
                            maxLength="4"
                            v-model="password">
                        <div class="styled-input__circle"></div>
                    </div>
                    <button type="button" class="styled-button" @click="submitPassword" >
                        <span class="styled-button__text">观看</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <!-- 绑定手机号 -->
    <div class="dialog bind" v-show="showLogin">
        <div class="">
            <h3>绑定手机号</h3>
            <div class="styled-input" style="width:100%">
                <input
                    type="number"
                    class="styled-input__input"
                    placeholder="手机号"
                    v-model="phoneNum"
                    @blur="hackBlurTop">
                <div class="styled-input__circle"></div>
            </div>
            <div class="clear">
                <div class="styled-input fl" style="width:60%">
                    <input ref="codeInput"
                        type="text"
                        class="styled-input__input"
                        placeholder="验证码"
                        @blur="hackBlurTop"
                        v-model="sysCode">
                    <div class="styled-input__circle"></div>
                </div>

                <div class="styled-input fr" @click="getCode" style="width:35%;">
                    <div class="code">{{ sendCodeText }}</div>
                </div>
            </div>
            <div class="btn" @click="submitLogin">
                绑定手机号
            </div>
        </div>
    </div>
    <div class="loading" v-show="isLoading">
        <div class="loading-icon">
            <div class="round"></div>
            <div class="round"></div>
            <div class="round"></div>
            <div class="round"></div>
            <div class="round"></div>
            <div class="round"></div>
            <div class="round"></div>
            <div class="round"></div>
        </div>
    </div>
</div>
</template>

<script>
import message from '../modules/message';
import conf from '../config';
// 
var JIM = new JMessage();
// 统计数据baseUrl
const statisticsBaseUrl = process.env.NODE_ENV=='production' ? "" : "http://39.97.245.17:12305";

// 阿里播放器对象
var player;

// 初始化页面高度，用于某些机型resize事件后，高度测不准问题
const iniClientHeight = window.innerHeight || document.documentElement.offsetHeight || document.body.offsetHeight;

// 获取url参数
const getQueryPara = function (paraName, dft = null) {
	var sUrl = location.href;
    sUrl = sUrl.replace("#/index", "");
	var sReg = '[\?&]{1}' + paraName + '=([^&]*)';
	var re = new RegExp(sReg);
	var rst = (sUrl.match(re));
	if (rst === null) return dft;
	return decodeURIComponent(rst[1]);
};

/**
 * 安全范围
 * 假设球在从0到10的线上运动，球本身直接2米，那球中心就只能在1-9的范围内运动，无法逾越
 */
function getSafeScope(allScope, radius, inputValue){
    let min = radius,
        max = allScope - radius;
    return inputValue>max ? max : (inputValue<min ? min : inputValue);
}

// 获取浏览器版本及语言
const browser = {
	// 版本
	versions: function() {
		const u = navigator.userAgent;
		return { //移动终端浏览器版本信息
			trident: u.indexOf('Trident') > -1, //IE内核
			presto: u.indexOf('Presto') > -1, //opera内核
			webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
			gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
			mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
			ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
			android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
			iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
			iPad: u.indexOf('iPad') > -1, //是否iPad
			weixin: u.indexOf('MicroMessenger') > -1, //是否微信
			webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
		};
	}(),
	// 语言
	language: (navigator.browserLanguage || navigator.language).toLowerCase()
};

const isIosAllScreen = (()=>{
    const width = window.screen.width,
        height = window.screen.height;
    return (width==375 && height==812)
        || (width==414 && height==896);
})();


export default {
    name:"index",

    data(){
        const that = this;
        return{
            audioShow: false,
            palyErrorShow: false,
            touchScreenX: 0,
            screenX: 0,
            // 
            livePlayUv: 1,
            // 
            showLogin: false,
            phoneNum: "",
            sysCode: "",
            userInfo: {},
            // 发送短信相关
            sendCodeData: {
                status: 1, // 1初始发送，2正在发送，3重新发送，4发送成功尚未转完cd
                cd: 60
            },
            // 倒计时
            countdownDay: 0,
            countdownHour: 0,
            countdownMinute: 0,
            countdownShow: false,
            // 横竖屏  false横屏
            isLoading: true,
            verticalScreen: true,
            verticaAboutShow: false,
            // 直播id
            liveId: getQueryPara("id"),
            liveTitle: "大鹅视频",

            videoPlayer:"",//播放器初始化
            // 竖版输入框样式切换
            chatShow: false,

            //画质改变
            thisQuality:1,
            quality:false,
            qualityFullScreen:false,
            qualityValue:"高清",
            allSource:"",
            password: "",
            // 聊天默认头像
            defaultAva: require("./../assets/defaultPic.png"),
            // 聊天默认官方头像
            defaultOfficialAva: require("./../assets/avatar.png"),

            //背景图片20191213
            // webBg:{
            //     backgroundImage:"url('https://haierzzfbmedia.oss-cn-beijing.aliyuncs.com/1576115619622_bg.jpg')",
            // },
            //背景图片通用
            webBg:{
                backgroundImage:"url(https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/default_background.png)",
            },
            // contentBg:{
            //     backgroundImage:"url(" + require("../assets/bg-font.png") + ")" ,
            // },
            li1:{
                backgroundImage:"url(" + require("../assets/shijian.png") + ")" ,
            },
            li2:{
                backgroundImage:"url(" + require("../assets/zhiyuandidian7.png") + ")" ,
            },
            li3:{
                backgroundImage:"url(" + require("../assets/gongsi.png") + ")" ,
            },
            fontFace:{
                backgroundImage:"url(" + require("../assets/bg-face.png") + ")" ,
            },
            // 横板直播未开始
            // videoBgImg: "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-waiting-0.png",
            // videoBg:{
            //     "background-image":"url(https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-loding-0.png)" ,
            // },
             videoBgImg: "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-loding-0.png",
            videoBg:{
                "background-image":"url(https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-loding-0.png)" ,
            },
            bgPic:true,
            // 用户信息
            userName: this.getCookie("userName") || "",
            userAvatar: this.getCookie("img") || this.defaultAva,
            token:this.getCookie("token") || "",
            unionid:this.getCookie("unionid") || "",
            jmsgUser:this.getCookie("jmsgUser") || "",
            jmsgPwd:this.getCookie("jmsgPwd") || "",

            // 干啥用的？
            position: "20%",

            // 显示聊天还是了解我，用这个字段命名合理吗？但是我懒得改了
            show:true,

            // 聊天输入内容
            cont:"",

            // 聊天 websocket
            wst:null,

            // OSS对象
            client:{},

            // 显示表情模块
            openEmoji:false,

            // 显示上传图片模块
            openPhoto:false,


            showSysMessage:false,  //显示系统消息
            message :{},    //websocket获得消息
            message1 :"",   //系统消息分割
            message2 :"",   //系统消息分割
            showPassword:false,  //展示密码框
            liveType: "",// 0普通 1密码

            liveInfo:{},//直播详情

            videoSource:"",//播放源
            streamId: "",
            liveForm: "直播",
            userId:this.getCookie("Id"),
            type: 1,//0是回看 1是直播

            // 已经获取直播
            isGetedLive: false,

            // 是否点击了”我要直播“按钮，命名是否合理？
            clickTVBOx:false,

            // 显示我要直播模块
            showedTVBox: false,

            // 是否悬浮置顶播放器
            showedTopViedo: false,

            //是否已登录
            isLogined: false,

            // 是否是原生app环境
            isAppEnv: (typeof window.webkit != 'undefined' && typeof window.webkit.messageHandlers != 'undefined' && typeof window.webkit.messageHandlers.Goshare != 'undefined') || typeof window.JsInterface !='undefined',
            isAndAppEnv: typeof window.JsInterface !='undefined',
            isIosAppEnv: (typeof window.webkit != 'undefined' && typeof window.webkit.messageHandlers != 'undefined' && typeof window.webkit.messageHandlers.Goshare != 'undefined'),

            // 上次点击video时间，用来模拟双击
            lastClickVideoTime: 0,

            // 聊天输入框是否聚焦
            chatInputIsFocused: false,

            // ws初次加载记录
            wstFirstLoaded: false,

            // 视频是否全屏
            videoIsFullScreen: false,
            // 视频播放状态，统计时常用
            playerStatus: "",

            // 观看人数
            viewsNumber: '',

            // 横竖屏状态检测
            isCrosswise: false,

            // 已经开始播放了
            videoIsFirstPlayed: false,

            // 聊天窗口上次是否在底部
            chatBoxLastTimeIsAtBottom: true,

            // 显示播放器控制台
            showedVideoControlBar: false,

            // 上次单击video时间
            lastClickVideoTimeForBar: 0,

            // 显示5s后隐藏控制栏
            isOverdueHiddenVideoControlBar: false,

            // 正在播放
            videoIsPlaying: false,

            // 页面实时高度
            clientHeight: iniClientHeight,

            // 微信登陆相关
            isWxEnv: navigator.userAgent.indexOf('MicroMessenger') > -1, //是否微信环境
            wxLoginCode: getQueryPara('code'), //微信登陆返回code
            wxLoginState: getQueryPara('state'), //微信返回state, 默认zzfb
            wxOpenId: '',
            wxUnionId: '',
            wxBindPhoneStatus: 0, // 微信未绑定手机号 0未知 1已绑定 2未绑定
            wxLoginStatus: 0, // 微信登陆状态 是否成功 0未开始 1进行中 2成功 3失败

            // 直播已结束
            liveIsOver: false,
            
            chatroomId: "",//聊天室Id
            chatroom: {},//聊天实例
            // 聊天列表
            chatList: [
                {
                    from_id: 1,
                    from_name: '官方消息',
                    msg_body: {
                        text: '大鹅提示请鹅友们友善发言，直播间文明由你我共同守护',
                    },
                },
            ],
            baseImgUrl: "https://app.ailive.cloud/app",

            showSysMessageTimer: {},
        }
    },

    watch: {

        // 这函数有什么意义？
        cont(val){
            val=val.replace(/(^\s*)/g, "");
        },

        // 视频是否全屏
        veoIsFullScreen(val){
            if(val){
            }
        },
        // 监听图片上传完成发送消息
        imgName(val){
            if(val){
                this.wst.send("img::" + val);
                console.log('ws发送图片：' + val);
            }
        },
        chatList(newVal, oldVal){
            this.$nextTick(()=>{
                var scrollTop = 0;
                if((this.$refs.chatList.offsetHeight+350) > document.getElementById("shows").offsetHeight){
                    scrollTop = (this.$refs.chatList.offsetHeight+350) - document.getElementById("shows").offsetHeight
                    console.log(scrollTop)
                }
                document.getElementById("shows").scrollTop = scrollTop;
            });
        },
    },

    computed: {
        videoPlayState(){
            if(this.videoPlayer){
                return this.videoPlayer.getStatus();
            }else{
                return '';
            }
        },

        // 满屏高度样式，替代100vh，以达到随浏览器高度实时变化
        fullHeightStyle(){
            return {
                height: this.clientHeight + 'px'
            };
        },

        // 需要伪全屏
        needFakeFullScreen(){
            return this.isCrosswise || this.videoIsFullScreen;
        },

        // 聊天输入框样式
        chatInputStyle(){
            const { chatInputIsFocused } = this;
            if(browser.versions.ios && !isIosAllScreen) {
                if(chatInputIsFocused) {
                    return {
                        'position': 'relative'
                    };
                } else {
                    return {
                        'position': 'fixed'
                    };
                }
            } else {
                return {};
            }
        },

        // 视频logo头像
        videoAvatar(){
            return (this.annoInfo&& typeof this.annoInfo.logoUrl=='string' && this.annoInfo.logoUrl!='') ? this.annoInfo.logoUrl : ingAvatar;
        },

        // 处理默认头像
        acquiescehead(){
            return function(url){
                if(url == "/img/default_main_pic.png"){
                    return "https://app.ailive.cloud/app/img/default_main_pic.png"
                }else{
                    return url
                }
            }
        },
        // 时间戳转化
        getTimeStr(){
            return function(str){
                if(!str){
                    return
                }
                var num = parseInt(str);
                var time = new Date(num);
                var year = time.getFullYear();
                var month = time.getMonth() + 1;
                var date = time.getDate();
                var hours = time.getHours();
                var minutes = time.getMinutes();
                if(month < 10){
                    month = "0" + month
                }
                if(date < 10){
                    date = "0" + date
                }
                if(hours < 10){
                    hours = "0" + hours
                }
                if(minutes < 10){
                    minutes = "0" + minutes
                }
                return year + "-" +　month + "-" + date + "    " + hours + ":" + minutes
            }
        },
        // 发送手机验证码按钮显示文字
        sendCodeText() {
			switch (this.sendCodeData.status) {
			case 1:
				return '获取验证码';
			case 2:
				return '发送中……';
			case 4:
				return '重新获取' + this.sendCodeData.cd + '\'';
			case 3:
				return '重新获取';
			}
        },
    },

    created() {
        // 禁用ios微信字体缩放
        (function () {
            if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
                handleFontSize();
            } else {
                if (document.addEventListener) {
                    document.addEventListener("WeixinJSBridgeReady", handleFontSize, false);
                } else if (document.attachEvent) {
                    document.attachEvent("WeixinJSBridgeReady", handleFontSize);
                    document.attachEvent("onWeixinJSBridgeReady", handleFontSize);
                }
            }
            function handleFontSize() {
                WeixinJSBridge.invoke('setFontSizeCallback', { 'fontSize': 0 });
                WeixinJSBridge.on('menu:setfont', function () {
                    WeixinJSBridge.invoke('setFontSizeCallback', { 'fontSize': 0 });
                });
            }
        })();
        // 进入页面统计
        this.statisticsUser("enter");

        // app环境初始化
        this.uriIni();

        // 获取流信息
        this.getInfo();

        // 如果已登陆，初始化
         
        if(browser.versions.ios && browser.versions.weixin && !browser.versions.android){
            this.wxLogin();
        }else if(!this.getCookie("mobile") || this.getCookie("mobile")==""){
            this.wxLogin();
        }else if(this.token && this.userName && this.userAvatar && this.jmsgUser && this.jmsgPwd){
            this.isLogined = true;
        }else{
            this.wxLogin();
        }
        // 监听滚动
        window.addEventListener('scroll', () => {
			let t = document.documentElement.scrollTop || document.body.scrollTop;
			if (typeof this.handleWindowScroll == 'function') {
				this.handleWindowScroll(t);
			}
        });
        // 监听屏幕变化
        window.addEventListener('resize', () => {
            this.doCheckResize();
        });
        // 定时任务
        setInterval(()=>{
            // 输入框bug
            if(this.chatInputIsFocused){
                if(typeof this.$refs.chatInputView.scrollIntoViewIfNeeded=='function'){
                    this.$refs.chatInputView.scrollIntoViewIfNeeded();
                } else {
                    this.$refs.chatInputView.scrollIntoView();
                }
                if(browser.versions.ios && !isIosAllScreen){
                    // let doc = document.documentElement || document.body;
                    // let st = doc.scrollHeight - doc.clientHeight;
                    // console.log(st);
                    // window.scrollTo(0, st);
                    window.scrollTo(0, 10000);
                }
            }

            // 监听播放状态，始终播放
            this.listenPlayStatus();
        }, 500);

        // 横竖屏状态检测
        this.checkResize();
        // 轮询直播状态，观看人数
        if(this.liveId){
            this.getLiveCount();
            setInterval(()=>{
                this.getLiveCount();
            }, 10000)
        }
    },
    mounted(){
        // 禁用微信前进后退
        document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
            WeixinJSBridge.call('hideToolbar');        // 隐藏底部状态栏
            // WeixinJSBridge.call('hideOptionMenu');     // 隐藏右上角的三个点的选项
            // WeixinJSBridge.call('showToolbar');        // 显示底部状态栏
            // WeixinJSBridge.call('showOptionMenu');     // 显示右上角的三个点的选项
        });

        function onBridgeReady(){
            WeixinJSBridge.call('hideToolbar');
        }
        
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        }else{
            onBridgeReady();
        }
        // 处理小屏遮挡播放按钮
        setTimeout(() => {
            if(document.getElementById("touch-mark")){
                document.getElementById("touch-mark").style.height = document.body.offsetHeight - 80 +  "px";
            }
        }, 200);
    },
    beforeDestory(){
        this.statisticsUser("exit");
    },
    methods: {
        // 控制栏显示5s后隐藏
        overdueHiddenVideoControlBar(){
            this.isOverdueHiddenVideoControlBar = false;
            let lastClickVideoTimeForBar = new Date().getTime();
            this.lastClickVideoTimeForBar = lastClickVideoTimeForBar;

            setTimeout(()=>{
                if(lastClickVideoTimeForBar == this.lastClickVideoTimeForBar && this.videoIsPlaying){
                    this.isOverdueHiddenVideoControlBar = true;
                }
            }, 5000);
        },
        // cookie存储
        setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = "expires="+ d.toUTCString();
            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        },
        // cookie读取
        getCookie(cname) {
            var name = cname + "=";
            var decodedCookie = decodeURIComponent(document.cookie);
            var ca = decodedCookie.split(';');
            for(var i = 0; i <ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        },
        // cookie删除
        deleteCookie(cname){

        },
        // 用户进入退出分享统计
        statisticsUser(type){
            if(this.getCookie("userId")){
                this.$http({
                    baseURL: statisticsBaseUrl,
                    url: "/api/v1/live/point",
                    method: "get",
                    params: {
                        action: type,
                        live_id: this.liveId,
                        user_id: this.getCookie("userId")
                    }
                }).then(res=>{
                    console.log("用户进入推出分享统计" + type, res);
                });
            }
        },
        // 播放时长统计
        statisticsTime(status){
            if(this.getCookie("userId")){
                this.$http({
                    baseURL: statisticsBaseUrl,
                    url: "/api/v1/player/point",
                    method: "get",
                    params: {
                        action: status,
                        live_id: this.liveId,
                        user_id: this.getCookie("userId")
                    }
                }).then(res=>{
                    console.log("播放时长统计", res);
                });
            }
        },
        // 监听页面滚动
        handleWindowScroll(t){
            this.hideTvbox();
            // 判断高度固定播放器位置 370
			if(t > px2px(330)){
                this.showedTopViedo = true;
            } else {
                this.showedTopViedo = false;
            }
        },
        // 
        touchStart(e, type){
            this.touchScreenX = e.touches[0].screenX;
        },
        // 
        touchMove(e, type){
            let width = document.getElementById("touch-mark").offsetWidth / 2;
            this.screenX = e.touches[0].screenX-this.touchScreenX
            if(this.screenX < 0 && type == 1){
                document.getElementById("touch-mark").style.left = this.screenX + "px";
                document.getElementsByClassName("m-fm small")[0].style.left = this.screenX + 10 + "px";
            }else if(this.screenX > 0 && type == 2){
                document.getElementById("touch-mark").style.left = this.screenX - width + "px";
                document.getElementsByClassName("m-fm small")[0].style.left = this.screenX + 10 + "px";
            }
        },
        // 
        touchEnd(e, type){
            let width = document.getElementById("touch-mark").offsetWidth / 2;
            // this.screenX
            if(this.screenX < -50 && type == 1){
                let Timer1 = setInterval(()=>{
                    this.screenX = this.screenX-10;
                    if(this.screenX > -width){
                        document.getElementById("touch-mark").style.left = this.screenX + "px";
                        document.getElementsByClassName("m-fm small")[0].style.left = this.screenX + 10 + "px";
                    }else{
                        document.getElementById("touch-mark").style.left = -width + "px";
                        document.getElementsByClassName("m-fm small")[0].style.left = -width + 10 + "px";
                        clearInterval(Timer1)
                    }
                }, 10);
            }else if(this.screenX > -50 && type == 1){
                let Timer2 = setInterval(()=>{
                    this.screenX = this.screenX+10;
                    if(this.screenX < 0){
                        document.getElementById("touch-mark").style.left = this.screenX  + "px";
                        document.getElementsByClassName("m-fm small")[0].style.left = this.screenX + 10 + "px";
                    }else{
                        document.getElementById("touch-mark").style.left = 0;
                        document.getElementsByClassName("m-fm small")[0].style.left = 10 + "px";
                        clearInterval(Timer2)
                    }
                }, 10);
            }else if(this.screenX > 50 && type == 2){
                let Timer3 = setInterval(()=>{
                    this.screenX = this.screenX+10;
                    if(this.screenX < width){
                        document.getElementById("touch-mark").style.left = this.screenX - width + "px";
                        document.getElementsByClassName("m-fm small")[0].style.left = this.screenX - width + 10 + "px";
                    }else{
                        document.getElementById("touch-mark").style.left = 0;
                        document.getElementsByClassName("m-fm small")[0].style.left = 10 + "px";
                        clearInterval(Timer3)
                    }
                }, 10);
            }else if(this.screenX < 50 && type == 2){
                let Timer4 = setInterval(()=>{
                console.log(this.screenX)   
                    this.screenX = this.screenX-10;
                    if(this.screenX > 0){
                        document.getElementById("touch-mark").style.left = this.screenX - width + "px";
                        document.getElementsByClassName("m-fm small")[0].style.left = this.screenX - width + 10 + "px";
                    }else{
                        document.getElementById("touch-mark").style.left = -width + "px";
                        document.getElementsByClassName("m-fm small")[0].style.left = -width + 10 + "px";
                        clearInterval(Timer4)
                    }
                }, 10);
            }
        },
        inputFocus(){
            this.chatInputIsFocused = true;
        },
        // 输入框聚焦
        handleInputFocus(){
            this.openEmoji = false;
            this.openPhoto = false;
            this.chatInputIsFocused = true;
            if(this.liveInfo.liveScreenStatus == 1){
                document.getElementsByClassName("m-fm")[0].style.left = 0;
            }
            // if(this.liveInfo.liveScreenStatus == 1){
                setTimeout(()=>{
                    var t =document.body.clientHeight;
                    window.scroll({top:t});
                }, 300);
            // }
            // liveScreenStatus
            // let flexheight = document.documentElement.clientHeight;
            // // 在页面整体加载完毕时
            // window.onload = () => {
            //     // 把获取到的高赋值给.flex
            //     document.getElementById('play').style.height = flexheight + "px";
            //     document.getElementById('play2').style.height = flexheight + "px";
            // };
            if(browser.versions.ios){
                // window.scrollTo(0, 0);
            }
        },

        // 聊天输入框失去焦点
        handleInputBlur(){
            this.openEmoji = false;
            this.openPhoto = false;
            this.chatInputIsFocused = false;
            if(this.liveInfo.liveScreenStatus == 1){
                document.getElementsByClassName("m-fm")[0].style.left = "10px";
            }
            this.$nextTick(()=>{
                this.hackBlur();
                if(browser.versions.ios){
                    this.$forceUpdate();
                }
            });
        },

        //获取直播详情
        getInfo(){
            this.$http({
                url: "/api/live/getLiveDetail/" + this.liveId,
                method: "get",
            }).then(res=>{
                if(res.code == 200){
                    let that = this;
                    // 判断横竖屏
                    if(res.data.liveEntity.liveScreenStatus == 0 && res.data.liveEntity.liveStatus != 2){
                        this.verticalScreen = false;
                    }else if(res.data.liveEntity.liveScreenStatus == 0 && res.data.liveEntity.liveStatus == 2){
                        this.verticalScreen = false;
                        this.videoBgImg = "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-over-0.png";
                        this.videoBg = {backgroundImage:"url(https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-over-0.png)"}
                    }else if(res.data.liveEntity.liveScreenStatus == 1 && res.data.liveEntity.liveStatus != 2){
                        this.verticalScreen = true;
                        // 竖版视频背景图
                        this.videoBgImg = "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-loding-1.png";
                        this.videoBg = {backgroundImage:"url(https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-loding-1.png)"};
                    }else if(res.data.liveEntity.liveScreenStatus == 1 && res.data.liveEntity.liveStatus == 2){
                        this.verticalScreen = true;
                        // 竖版视频背景图
                        this.videoBgImg = "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-over-1.png";
                        this.videoBg = {backgroundImage:"url(https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/vertical-over-1.png)"};
                    }
                    this.liveTitle = res.data.liveEntity.liveTitle;
                    document.title = this.liveTitle;
                    // 背景图
                    this.webBg = "backgroundImage:url(" + res.data.liveEntity.liveBackground + ")";
                    // 视频地址
                    if(this.liveId == 1622){
                        this.videoSource = "https://pull.lanbenzi.cn/hiNews/dailyNews_36952_1592461557.m3u8?auth_key=1592468757-0-0-cce781be143d05404fbabc1d1b85d5b5";
                    }else{
                        if(res.data.liveEntity.liveStatus == 1){
                            this.videoSource = res.data.streamUrl.m3u8_lhd;
                        }else if(res.data.streamUrl.playUrl != null){
                            this.videoSource = res.data.streamUrl.playUrl;
                        }
                    }
                    // 倒计时
                    if(res.data.liveEntity.liveStatus == 0){
                        this.countdownShow = true;
                        this.countCountdown(res.data.liveEntity.liveBeginTime);
                    }
                    this.liveInfo = res.data.liveEntity;
                    // 直播密码
                    this.liveType = res.data.liveEntity.liveType;
                    if(this.liveType == 0 || this.getCookie("passwordId") == res.data.liveEntity.id + "&" + res.data.liveEntity.livePassword){
                        
                    }else{
                        this.openPassword();
                    }
                    this.livePassword = res.data.liveEntity.livePassword;
                    this.streamId = res.data.liveEntity.liveStreamId;
                    setTimeout(function(){
                        // 延时处理防止初始化时获取不到dom元素，撤下加载页延时防止播放器闪动
                        that.isLoading = false;
                        if(that.liveInfo.liveStatus == 1 || that.liveInfo.liveStatus == 3 || that.liveInfo.liveStatus == 4){
                            that.iniVideo();
                        }
                    }, 100)
                    // 微信分享
                    this.getShareDate(res.data.liveEntity);
                    if(this.token && this.userName && this.userAvatar && this.jmsgUser && this.jmsgPwd){
                        // this.linkWebket();
                        this.getImAuthPayload();
                    }
                }else if(res.code == 666){
                    message.error(res.msg);
                }else if(res.code == 601){
                    message.error("本视频已被删除");
                }else{
                    message.error("网络错误");
                }
            })
        },
        // 
        getCode(){
            if(!this.phoneNum){
                return message.warning('请输入手机号', 1200);
            }
            if(!/^1[0-9]{10}$/.test(this.phoneNum)){
                return message.warning('手机号格式错误', 1200);
            }
            if(this.sendCodeData.status!=1 && this.sendCodeData.status!=3) {
                return console.log('重复点击无效');
            }

            this.sendCodeData.status = 2;

            this.$http.get("/api/user/getSmsCaptcha?mobile=" + this.phoneNum).then((res) =>{
                if(res.data.code == 200){;
                    message.success('发送成功,请注意查收', 1200);
                    // this.$refs.codeInput.focus();
                    // 发送倒计时
                    const cd = ()=> {
                        setTimeout(()=>  {
                            if (this.sendCodeData.cd <= 0) {
                                this.sendCodeData.status = 3;
                            } else {
                                this.sendCodeData.cd -= 1;
                                cd();
                            }
                        }, 1000);
                    };
                    this.sendCodeData.cd = 59;
                    this.sendCodeData.status = 4;
                    cd();
                }else if(res.data.code == 500){
                    this.sendCodeData.status = 1;
                    this.phoneNum = "";
                    // alert(res.data.msg);
                    message.error('操作失败,请稍后再试！', 1200);
                }
            });
        },
        // 
        submitLogin(){
            let userInfo = {};
            if(this.sysCode=="" || this.sysCode.length > 4){
                message.error("请输入正确的验证码", 1200);
            }
            if(browser.versions.ios && browser.versions.weixin && !browser.versions.android){
                userInfo = {
                    username: this.userInfo.username,
                    mobile: this.phoneNum,
                    token: this.userInfo.token,
                    openid: this.userInfo.openid,
                    unionid: this.userInfo.unionid,
                    smsCaptcha: this.sysCode,
                    headImg: this.userInfo.headImg,
                }
            }else{
                userInfo = {
                    username: this.getCookie("userName"),
                    mobile: this.phoneNum,
                    token: this.getCookie("token"),
                    openid: this.getCookie("openid"),
                    unionid: this.getCookie("unionid"),
                    smsCaptcha: this.sysCode,
                    headImg: this.getCookie("img"),
                }
            }
            this.$http({
                url: "/api/user/wechatLogin",
                method: "post",
                data: userInfo
            }).then(res=>{
                if(res.code == 200){
                    this.showLogin = false;
                    setCookie("mobile", this.phoneNum, 30)
                    console.log(res.data);
                }else{
                    message.error(res.msg, 1200);
                }
            })
        },
        // 查询观看人数
        getLiveCount(){
            this.$http({
                url: "/api/live/getLiveInfoCron/" + this.liveId,
                method: "get",
            }).then(res=>{
                if(res.code == 200){
                    this.livePlayUv = res.data.livePlayUv
                    this.liveInfo.liveStatus == res.data.liveStatus;
                    if(window.sessionStorage.getItem("liveStatus") == null){
                        window.sessionStorage.setItem("liveStatus", res.data.liveStatus);
                    }else if(window.sessionStorage.getItem("liveStatus") != res.data.liveStatus){
                        window.sessionStorage.setItem("liveStatus", res.data.liveStatus);
                        if(res.data.liveStatus == 1 || res.data.liveStatus == 3 || res.data.liveStatus == 4){
                            this.getInfo();
                        }
                    }
                }
            });
        },
        // 获取微信分享权限
        getShareDate(shareData){
            // let h5Url = location.href.split('#')[0];
            // let h5Url2 = "";
            // if(h5Url.charAt(h5Url.length-1) == "/"){
            //     h5Url = h5Url.substring(0,h5Url.length - 1)
            // }else{
            //     h5Url2 = h5Url
            // }
            let liveType = "【直播】";
            let that = this;
            if(this.liveInfo.liveStatus == 3){
                liveType = "【回放】"
            }
            if(this.liveInfo.liveStatus == 4){
                liveType = "【回放】"
            }
            this.$http({
                url: "/api/jsapiTicketH5",
                method: "post",
                data: {
                    h5Url: location.href.split('#')[0],
                    type: 0,
                }
            }).then(res=>{
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: 'wx65be8936093075fe', // 必填，公众号的唯一标识
                    timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ["updateAppMessageShareData", "onMenuShareAppMessage",  "updateTimelineShareData", "onMenuShareTimeline",  "onMenuShareWeibo"] // 必填，需要使用的JS接口列表
                });
                wx.ready(function(){
                    // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                    wx.updateAppMessageShareData({ 
                        title: liveType + shareData.liveTitle, // 分享标题
                        desc: shareData.liveTitle + "正在直播，由“大鹅视频”全程提供直播服务", // 分享描述
                        link: location.origin + "/h5/?id=" + shareData.id, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/default_share.png", // 分享图标
                        success: function () {
                        // 设置成功
                            that.statisticsUser("share");
                        },
                        error: function(){
                            alert(11111);
                        }
                    })
                    wx.onMenuShareAppMessage({ 
                        title: liveType + shareData.liveTitle, // 分享标题
                        desc: shareData.liveTitle + "正在直播，由“大鹅视频”全程提供直播服务", // 分享描述
                        link: location.origin + "/h5/?id=" + shareData.id, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/default_share.png", // 分享图标
                        success: function () {
                        // 设置成功
                        that.statisticsUser("share");
                        }
                    })
                    wx.onMenuShareTimeline({ 
                        title: liveType + shareData.liveTitle, // 分享标题
                        desc: shareData.liveTitle + "正在直播，由“大鹅视频”全程提供直播服务", // 分享描述
                        link: location.origin + "/h5/?id=" + shareData.id, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/default_share.png", // 分享图标
                        success: function () {
                        // 设置成功
                        that.statisticsUser("share");
                        }
                    })
                    wx.updateTimelineShareData({ 
                        title: liveType + shareData.liveTitle, // 分享标题
                        desc: shareData.liveTitle + "正在直播，由“大鹅视频”全程提供直播服务", // 分享描述
                        link: location.origin + "/h5/?id=" + shareData.id, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/default_share.png", // 分享图标
                        success: function () {
                        // 设置成功
                        that.statisticsUser("share");
                        }
                    })
                    wx.onMenuShareWeibo({ 
                        title: liveType + shareData.liveTitle, // 分享标题
                        desc: shareData.liveTitle + "正在直播，由“大鹅视频”全程提供直播服务", // 分享描述
                        link: location.origin + "/h5/?id=" + shareData.id, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: "https://ailive-api.oss-cn-zhangjiakou.aliyuncs.com/default/default_share.png", // 分享图标
                        success: function () {
                        // 设置成功
                        that.statisticsUser("share");
                        }
                    })
                });
                wx.error(function(res){
                    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                });
            });
        },
        // 开播倒计时计算
        countCountdown(beginTime){
            let that = this;
            console.log("倒计时", beginTime - new Date().valueOf());
            if(beginTime - new Date().valueOf() <= 0){
                this.countdownShow = false;
                return
            }
            that.countCount(beginTime);
            let Timer = setInterval(function(){
                if(that.liveInfo.liveStatus != 0){
                    clearInterval(Timer);
                    that.countdownShow = false;
                }
                that.countCount(beginTime);
            }, 1000)
        },
        // 计算
        countCount(beginTime){
            let times = beginTime - new Date().valueOf();
            if(times < 2000){
                this.getInfo();
            }
            this.countdownDay = Math.floor(times / 86400000);
            this.countdownHour = Math.floor(times % 86400000 / 3600000);
            this.countdownMinute = Math.floor(times % 86400000 % 3600000 / 60000);
        },
        // 
        changeStyle(val){
            if(val == 1){
                this.show = true;
                this.position = '20%';
            }
            if(val == 2){
                this.show = false;
                this.position = '70%';
                this.$nextTick(() => {
                    this.heightRecord = this.$refs.activ.offsetHeight;
                })
            }
        },
        //聊天初始化
        getImAuthPayload(){
            this.$http({
                url: "/api/jmsgAuth",
                method: "get"
            }).then(res=>{
                JIM.init({
                    "appkey": res.data.appkey,
                    "random_str": res.data.random_str,
                    "signature": res.data.signature,
                    "timestamp": res.data.timestamp,
                    "flag" : 1
                }).onSuccess((data)=>{
                    console.log("Success", data)
                    this.JIMlogin();
                    //data.code 返回码
                    //data.message 描述
                }).onFail((data)=>{
                    console.log("Fail", data)
                });
            });
        },
        JIMlogin(){
            console.log("用户信息",this.jmsgUser, this.jmsgPwd)
            JIM.login({
                "username": this.jmsgUser,
                "password": this.jmsgPwd,
                // "is_md5": true,
            }).onSuccess((data)=>{
                console.log("登录成功", data);
                this.enterChatroom();
            }).onFail((data)=>{
                console.log("loginFail", data);
                if(data.code == "880107"){
                    this.enterChatroom();
                }
            });
        },
        // 进入聊天室
        enterChatroom(){
            JIM.enterChatroom({
                "id": this.liveInfo.jmsgId,
            }).onSuccess((data)=>{
                console.log("加入聊天室", data);
                // IOS有几率出现消息重复，可能是因为进入两次
                this.chatList = [{
                    from_id: 1,
                    from_name: '官方消息',
                    msg_body: {
                        text: '大鹅提示请鹅友们友善发言，直播间文明由你我共同守护',
                    },
                }];
                // 聊天室消息监听
                JIM.onRoomMsg((data)=>{
                    console.log("聊天室消息监听", data)
                    if(data.room_id == this.liveInfo.jmsgId){
                        if(data.content.msg_body.text){
                            this.chatList.push(data.content);
                        }else if(data.content.msg_body.custom){

                        }
                    }
                });
            }).onFail((data)=>{
                console.log("enterChatroomFail", data)
                if(data.code == "881507"){
                    // 聊天室消息监听
                    this.exitChatroom();
                }
            });
        },
        // 退出聊天室
        exitChatroom(){
            JIM.exitChatroom({
                "id": this.liveInfo.jmsgId,
            }).onSuccess((data)=>{
                console.log("exitChatroomSuccess", data)
                this.enterChatroom();
                //data.code 返回码
                //data.message 描述
            }).onFail((data)=>{
                console.log("exitChatroomFail", data)
                // 同上
            });
        },
        // 聊天室发送文本消息
        sendChatroomMsg(){
            if(this.cont == ""){
                return false
            }

            let sendMSg = this.cont;
            this.cont="";
            JIM.sendChatroomMsg({
                "target_rid": this.liveInfo.jmsgId,
                // "target_rid": "23747459",
                "content": sendMSg,
                // "extras": "enter",
            }).onSuccess((data, msg)=>{
                console.log("sendChatroomMsgSuccess", data, msg)
                this.chatList.push({from_name: this.userName, msg_body: {text: sendMSg}})
                this.$forceUpdate();
                //data.code 返回码
                //data.message 描述
            }).onFail((data)=>{
                console.log("sendChatroomMsgFail", data)
                // 同上
            });
        },
        // 聊天室发送自定义消息
        sendChatroomCustom(){
            JIM.sendChatroomCustom({
                "target_rid": this.chatroomId,
                // "target_rid": "23747459",
                "custom": {"custom": "1"},
                // "extras": "enter",
            }).onSuccess((data, msg)=>{
                console.log("sendChatroomCustomSuccess", data, msg)
                //data.code 返回码
                //data.message 描述
            }).onFail((data)=>{
                console.log("sendChatroomCustomFail", data)
                // 同上
            });
        },
        // 初始化播放器
        iniVideo(){
            console.log("videoSource", this.liveInfo.liveStatus, this.videoSource)
            if(browser.versions.android){

            }
            var that = this;
            player = new Aliplayer({
                "id": "player-con",
                "source": that.videoSource,
                // "source":"http://vod.ailive.cloud/liveRecord/77bd17852bce890292935dba4d4483b5/ai-live/6e1a9fcb41174902ba8433e32d86e1a9/2019-11-15-08-29-44_2019-11-15-12-14-51.m3u8",
                "width": "100%",
                "height": "100%",
                "autoplay":false,
                "isLive": that.liveInfo.liveStatus == 1 ? true : false,
                "playsinline": true,
                "preload": true,
                "showBuffer":true,
                "controlBarVisibility": "hover",
                "useH5Prism": true,
                "extraInfo":{
                    "crossOrigin":"anonymous",
                    "liveRetry":1,
                },
                "x5_type": that.liveInfo.liveScreenStatus == 0 ? false : "h5",
                // "x5_video_position": "top",
                // "x5_fullscreen": true,
                // 直播结束有一张， videoBg字段还有一张
                "cover": that.videoBgImg,
            }, function (player) {
                console.log("The player is created")
                setTimeout(() => {
                    document.getElementsByClassName("outter")[0].addEventListener("click", function(){
                        that.audioShow = true;
                    })
                    document.getElementsByClassName("outter")[0].addEventListener("touch", function(){
                        that.audioShow = true;
                    })
                }, 500);
                that.bgPic = false;
                player.on('onM3u8Retry', ()=>{
                    that.liveIsOver = true;
                    that.bgPic = true;
                    that.audioShow = false;
                    that.palyErrorShow = true;
                });
                player.on('error', ()=>{
                    that.liveIsOver = true;
                    that.bgPic = true;
                    that.audioShow = false;
                    that.palyErrorShow = true;
                });
                player.on("pause", ()=>{
                    that.audioShow = false;
                })

                player.on('liveStreamStop', ()=>{
                    // this.liveIsOver = true;
                });

                player.on('canplay', ()=>{
                    that.liveIsOver = false;
                });
                

                player.on('showBar', ()=>{
                    // player.getComponent('fakeFullScreen').$html.style.display = 'block';
                    that.showedVideoControlBar = true;
                    that.overdueHiddenVideoControlBar();
                });

                player.on('hideBar', ()=>{
                    that.showedVideoControlBar = false;
                    that.quality = false;
                    that.qualityFullScreen = false;
                    // console.log("隐藏")
                });

                player.on('ready', ()=>{
                    that.overdueHiddenVideoControlBar();
                });
                // 同层播放样式监听
                player.on("x5requestFullScreen", function(){
                    // that.setLayout();
                    // 进入同层播放时改变聊天内容的位置，防止安卓全屏同层播放时输入框上移遮挡聊天内容
                    if(browser.versions.android){
                        document.getElementById("touch-mark").style.height = document.body.offsetHeight - 100 +  "px";
                    }
                });
                player.on("x5cancelFullScreen", function(){
                    // that.setLayover();
                    // 退出同层播放时需要等待退出后的样式加载完成再改变聊天内容的位置
                    setTimeout(()=>{
                        if(browser.versions.android){
                            document.getElementById("touch-mark").style.height = document.body.offsetHeight - 80 +  "px";
                        }
                    }, 200)
                });
                setInterval(function(){
                    if(that.playerStatus != player.getStatus()){
                        that.playerStatus = player.getStatus();
                        if(that.playerStatus == "playing"){
                            that.statisticsTime("playing");
                        }else if(that.playerStatus == "pause"){
                            that.statisticsTime("pause");
                        }
                    }
                }, 1000);
            });
            this.videoPlayer = player;
        },
        // 监听同屏播放
        setLayout(){
            var a = document.getElementsByClassName("vertical")[0];
            var b = document.getElementsByClassName("head")[0];
            a.style.marginTop = 0;
            a.style.top = 0;
            b.className += " z-top vertical-head"; 
        },
        // 
        setLayover(){
            var a = document.getElementsByClassName("vertical")[0];
            var b = document.getElementsByClassName("head")[0];
            a.style.marginTop = "4.53333rem";
            a.style.top = 0;
            b.className = a.className.replace( new RegExp( "(\\s|^)z-top vertical-head(\\s|$)" ), " " ); 
        },
        // 
        playerStop(){
            if(this.videoIsPlaying){
                player.pause();
            } else {
                player.play();
            }
        },
        
        // 全屏监听
        fullScreen(e){
            console.log("我全屏啦");
            // this.videoIsFullScreen = true;
            this.doCheckResize();
        },

        // 小屏继续播放
        SmallScreen(player){
            // 小屏后继续播放
            player.play();
            this.doCheckResize();
        },
        // DataURL转Blob对象
        dataURLToBlob(dataurl){
            var arr = dataurl.split(',');
            var mime = arr[0].match(/:(.*?);/)[1];
            var bstr = atob(arr[1]);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        },

        openPassword(){
            this.showPassword = true;
            setTimeout(function () {
                document.body.classList.add('on-start');
            }, 100);
            
            setTimeout(function () {
                document.body.classList.add('document-loaded');
            }, 500);
        },

        //获取焦点检查登录状态
        checkLogin(){
            if(!this.getCookie("token")){
                message.error('请微信授权后发言', 1200);
                this.wxLogin();
            }
        },


        unfoldEmoji(){
            document.getElementById('inputId').blur();
            this.openEmoji=!this.openEmoji;
            if(this.openEmoji){
                this.openPhoto = false;
            }
        },

        unfoldPhoto(){
            document.getElementById('inputId').blur();
            this.openPhoto = !this.openPhoto;
            if(this.openPhoto){
                this.openEmoji = false;
            }
        },

        // oss图片上传初始化
        initialize(){
            this.$http.get("/oss/auth/url", {
            }).then((res) => {
                // console.log(res.data)
                if(res.data.code == 500){
                    this.isLogined = false;
                    this.softLogout();
                    // this.openLogin();
                    return message.warning('用户信息已失效，请重新登录', 1200);
                } else {
                    this.client = new OSS({
                        region: 'oss-cn-beijing',
                        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式来进行API访问
                        accessKeyId: res.data.AccessKeyId,
                        accessKeySecret: res.data.AccessKeySecret,
                        stsToken: res.data.SecurityToken,
                        bucket: 'haierzzfb',
                        useFetch: false,
                        secure:true,
                        multiSelection: false,
                    });
                }
            }).catch((error) => {
                // alert('出错了');

            });
        },

        // 聊天窗口滚动到底部,默认强制执行
        chatBoxScrollToBottom(force = true){
            // console.log('调用滚动到底部', force);
            // console.log('上次是否在底部', this.chatBoxLastTimeIsAtBottom);
            if(this.chatBoxLastTimeIsAtBottom || this.force){
                // console.log('真实执行滚动到底部', force);
                this.$refs.ol.scrollTop = this.$refs.chatList.offsetHeight;
            }
        },

        //验证密码
        submitPassword(){
            // console.log(this.livePassword,parseInt(this.password))
            if(!this.password){
                return message.warning('请输入直播密码', 1200);
            }
            if(this.livePassword !== this.password){
                return message.warning('密码输入错误', 1200);
            }
            message.success('欢迎您' + this.userName + "！", 1500);
            this.setCookie("passwordId", this.liveId + "&" + this.password, 1);
            this.showPassword = false;
        },

        // 对uri特殊处理下
        specCookUriData(str){
            if(typeof str=='string'){
                return str.replace('#/index', '');
            } else {
                return str;
            }
        },

        // 从uri初始化
        uriIni(){
            if(!this.isAppEnv) return;
            this.testText = this.specCookUriData(getQueryPara('userid'));
            console.log(this.specCookUriData(getQueryPara('userid')));
            var userId = this.specCookUriData(getQueryPara('userid'));
            this.token = this.specCookUriData(getQueryPara('token'));
            this.userName = this.specCookUriData(getQueryPara('username'));
            this.userAvatar = this.specCookUriData(getQueryPara('img'));
            this.setCookie("token", this.specCookUriData(getQueryPara('token')), 30);
            // 标记已经登陆
            this.isLogined = true;
        },
        // 分享转发
        toShare(){
            const { liveTitle, liveInfo } = this;
            let params = {
                title: liveTitle || '大鹅视频直播平台',
                content: liveInfo.liveDescription || '本直播由大鹅视频团队提供支持',
                url: window.location.href,
                img: liveInfo.liveLogoImg,
            };
            if(this.isIosAppEnv){
                window.webkit.messageHandlers.Goshare.postMessage(params);
            } else if(this.isAndAppEnv){
                window.JsInterface.Goshare(params.title, params.content, params.url, params.img);
            }
        },

        // 这个方法是为了苹果手机失去焦点后，布局无法自动归位，不加延时就会收不回去
        hackBlur(){

            setTimeout(() => {
                let currentPosition;
                let speed = 1; //页面滚动距离
                currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
                currentPosition -= speed;
                window.scrollTo(0, currentPosition); //页面向上滚动
                currentPosition += speed; //speed变量
                window.scrollTo(0, currentPosition); //页面向下滚动
            }, 200);

            // let doc = document.documentElement || document.body;
            // let st = doc.scrollHeight - doc.clientHeight;
            // console.log(st);
            // window.scrollTo(0, st);
            // // ios浏览器会卡住
            // if(browser.versions.ios){
            //     this.$refs.pageBottomTag.scrollIntoView(false);
            // }
        },
        hackBlurTop(){
            let doc = document.documentElement || document.body;
            let st = doc.scrollHeight - doc.clientHeight;
            // console.log(st);
            window.scrollTo(0, doc.scrollTop + 1);
        },

        doCheckResize(){
            let doc = document.body;
            if (window.orientation === 180 || window.orientation === 0) { 
                console.log('竖屏状态！');
                this.isCrosswise = false;
                doc.style.backgroundColor = '#fff';
                if(this.qualityFullScreen){
                    this.qualityFullScreen = false;
                }
            } 
            if (window.orientation === 90 || window.orientation === -90 ){ 
                console.log('横屏状态！');
                this.isCrosswise = true;
                doc.style.backgroundColor = '#000';
                if(this.quality){
                    this.quality = false;
                }

                // 产品让改成每次全屏播放都有提示
                this.haveReadDisernHint = false;
            }
            
            // 如果ios app内,无需更新高度,更新后会出错
            if(!this.isIosAppEnv || this.isCrosswise){
                if(browser.versions.android && this.chatInputIsFocused){
                    return;
                }
                this.clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
                console.log('页面大小变化', this.clientHeight);
                if (browser.versions.ios && browser.versions.weixin) { 
                    this.clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                }
            } else {
                this.clientHeight = iniClientHeight;
            }
        },

        // 检测手机横竖屏状态
        checkResize(){
            let that = this;
            that.doCheckResize();
            
            //判断手机横竖屏状态：
            window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", ()=>{
                that.doCheckResize();
            }, false); 
        },

        shiftFullVideo(){
            if(this.isIosAppEnv) {
                window.webkit.messageHandlers.GotoFullscreen.postMessage({});
            } else if(this.isAndAppEnv){
                window.JsInterface.GotoFullscreen();
            } else {
                this.videoIsFullScreen = !this.videoIsFullScreen;
            }
            this.overdueHiddenVideoControlBar();
        },

        // 劫持全屏按钮点击事件
        hijackFullBtnClick(){
            let eles = document.getElementsByClassName('prism-fullscreen-btn');
            let that = this;
            console.log('满屏按钮个数：', eles.length);
            if(eles.length > 0){
                let ele = eles[0];

                ele.onclick = (e)=>{
                    e.preventDefault();
                    if (e && e.stopPropagation){
                        e.stopPropagation()
                    }else{
                        window.event.cancelBubble = true;
                        window.event.retuenValue = false;
                    }

                    console.log('点击全屏按钮', e);
                    // that.shiftFullVideo();
                    return false;
                };

                ele.ontouchstart = (e)=>{
                    e.preventDefault();
                    if (e && e.stopPropagation){
                        e.stopPropagation()
                    }else{
                        window.evenlt.canceBubble = true;
                        window.event.retuenValue = false;
                    }

                    that.shiftFullVideo();
                    console.log('触摸全屏按钮', e);
                    return false;
                };
            }
        },

        showTvbox(){
            let index = 0;
            document.getElementsByTagName("video")[0].style
            this.showedTVBox = true;
            this.clickTVBOx = !this.clickTVBOx;
        },
        hideTvbox(){
            
        },

        // 关闭页面
        closePage(){
            this.statisticsUser("exit");
            if(this.isIosAppEnv){
                // 必须传一个空参数
                window.webkit.messageHandlers.ClosePage.postMessage({});
            } else if(this.isAndAppEnv){
                window.JsInterface.ClosePage();
            }
        },

        // 监听播放状态
        listenPlayStatus(){
            if(player && typeof player.getStatus=='function'){
                let sts = player.getStatus();
                if(typeof sts=='string'){
                    if(sts!='playing' &&  sts!='play' &&  sts!='init' &&  sts!='error'){
                        if(this.isLogined && typeof player.play=='function'){
                            // 永远播放
                            // player.play();
                        }
                    }

                    if(sts=='playing' || sts=='play'){
                        this.videoIsFirstPlayed = true;
                        this.videoIsPlaying = true;
                    } else {
                        this.videoIsPlaying = false;
                    }

                    if(sts == 'error'){
                        if(this.videoIsFullScreen){
                            this.shiftFullVideo();
                        }
                    }

                    if(sts == 'error' || sts=='ended'){
                        this.liveIsOver = true;
                    } else {
                        this.liveIsOver = false;
                    }
                }
            } else {
                if(this.videoIsFullScreen){
                    this.shiftFullVideo();
                }
            }
        },

        shiftVideoPlay(){
            if(this.videoIsPlaying){
                player.pause();
            } else {
                player.play();
            }
        },
        //切换分辨率
        shiftQuality(){
            this.quality = true;
            this.isOverdueHiddenVideoControlBar = true;
            // console.log(111)
        },
        //切换分辨率(横屏)
        shiftQualityFullScreen(){
            this.qualityFullScreen = true;
            this.isOverdueHiddenVideoControlBar = true;
        },
        //改变画质
        changeQuality(val){
            this.quality = false;
            this.qualityFullScreen = false;
            this.showedVideoControlBar = true;
            this.overdueHiddenVideoControlBar();
            if(val == 1){
                this.thisQuality = 1;
                this.qualityValue = "高清";
                player.pause();
                player.loadByUrl(this.allSource.m3u8_lhd.replace("http:",""));
                player.play();

            }else if(val == 2){
                this.thisQuality = 2;
                this.qualityValue = "标清";
                player.pause();
                player.loadByUrl(this.allSource.m3u8_lsd.replace("http:",""));
                player.play();

            }else if(val == 3){
                this.thisQuality = 3;
                this.qualityValue = "流畅";
                player.pause();
                player.loadByUrl(this.allSource.m3u8_lld.replace("http:",""));
                player.play();
            }
        },
        // 阅读提示
        readDisernHint(){
            this.haveReadDisernHint = true;
        },

        // 微信登陆
        async wxLogin(){
            if(this.isLogined || !this.isWxEnv) return;

            const {wxLoginCode, wxLoginState, wxLoginStatus} = this;

            if(wxLoginStatus==0){
                if(wxLoginState && wxLoginState.indexOf('zzfb') != -1){
                    this.wxLoginStatus = 1;
                    const res = await this.$http.get("/api/user/wechatAuthLoginH5?code=" + this.wxLoginCode + "&type=0");
                    console.log("微信登录信息", res.data)
                    if(res.code == 200){
                        this.isLogined = true;
                        this.wxLoginStatus = 2;
                        this.userInfo = res.data;
                        this.userName = res.data.username;
                        this.userAvatar = res.data.headImg;
                        this.setCookie("token", res.data.token, 30);
                        this.setCookie("mobile", res.data.mobile, 30);
                        this.setCookie("userName", res.data.username, 30);
                        this.setCookie("img", res.data.headImg, 30);
                        this.setCookie("unionid", res.data.unionid, 30);
                        this.setCookie("openid", res.data.openid, 30);
                        this.setCookie("jmsgUser", res.data.jmsgUser, 30);
                        this.setCookie("jmsgPwd", res.data.jmsgPwd, 30);
                        if(!res.data.mobile){
                            this.showLogin = true;
                        }
                        if(this.liveInfo != {}){
                            this.getImAuthPayload();
                        }
                    } else if(res.code == 500 && res.msg == "Internal Server Error"){
                       // 登录失败怎么办呢？可能是授权失效，尝试再次授权，可能会进入死循环
                        const baseUrl = process.env.NODE_ENV=='production' ? 'https://gateway.ailive.cloud/h5' : 'https://test.ailive.cloud/h5';
                        // const baseUrl = process.env.NODE_ENV=='production' ? 'http://app.ailive.cloud/app' : 'https://test.ailive.cloud/app';
                        const loginUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
                            + 'wx65be8936093075fe'
                            + '&redirect_uri='
                            + encodeURI(baseUrl + '?id=' + this.liveId)
                            + '&response_type=code&scope=snsapi_userinfo&state=zzfb#wechat_redirect';
                        // message.success(baseUrl + '?id=' + this.liveId);
                        location.href = loginUrl;
                    } else {
                        this.wxLoginStatus = 3;
                        console.log(res.data.msg);
                    }
                } else {
                    const baseUrl = process.env.NODE_ENV=='production' ? 'https://gateway.ailive.cloud/h5' : 'https://test.ailive.cloud/h5';
                    // const baseUrl = process.env.NODE_ENV=='production' ? 'http://app.ailive.cloud/app' : 'https://test.ailive.cloud/app';
                    const loginUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
                        + 'wx65be8936093075fe'
                        + '&redirect_uri='
                        + encodeURI(baseUrl + '?id=' + this.liveId)
                        + '&response_type=code&scope=snsapi_userinfo&state=zzfb#wechat_redirect';
                    // message.success(baseUrl + '?id=' + this.liveId);
                    location.href = loginUrl;
                }
            } else if(wxLoginStatus == 3)  {
                // 登录失败怎么办呢？可能是授权失效，尝试再次授权，可能会进入死循环
                const baseUrl = process.env.NODE_ENV=='production' ? 'https://gateway.ailive.cloud/h5' : 'https://test.ailive.cloud/h5';
                    // const baseUrl = process.env.NODE_ENV=='production' ? 'http://app.ailive.cloud/app' : 'https://test.ailive.cloud/app';
                    const loginUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
                        + 'wx65be8936093075fe'
                        + '&redirect_uri='
                        + encodeURI(baseUrl + '?id=' + this.liveId)
                        + '&response_type=code&scope=snsapi_userinfo&state=zzfb#wechat_redirect';
                    // message.success(baseUrl + '?id=' + this.liveId);
                    location.href = loginUrl;
            } else {
                return;
            }
        },
        // 开始上传图片1
        startUploadImg(){
            var file = document.getElementById("file");
            file.click();
        },
        uploadImg(){
            let that = this;
            var fileMsg = this.chatroom.sendFile({
                type: 'image',
                text: JSON.stringify({msgType: 2, content: ""}),
                fileInput: document.getElementById("file"),
                uploadprogress: function(obj) {
                    console.log('文件总大小: ' + obj.total + 'bytes');
                    console.log('已经上传的大小: ' + obj.loaded + 'bytes');
                    console.log('上传进度: ' + obj.percentage);
                    console.log('上传进度文本: ' + obj.percentageText);
                },
                uploaddone: function(error, file) {
                    console.log('上传' + (!error?'成功':'失败'), error, file);
                },
                beforesend: function(msg) {
                    console.log('正在发送聊天室image消息, id=' + msg.idClient, msg);
                },
                done: function sendChatroomMsgDone(error, msg){
                    if(error == null){
                        msg.text = JSON.parse(msg.text);
                        msg.text.msgType = 4;
                        that.chatList.push(msg);
                    }
                    console.log(error, msg);
                    that.$nextTick(() => {
                        that.openEmoji = false;
                        that.openPhoto = false;
                        that.chatBoxScrollToBottom();
                    });
                }
            });
        },
    },
}
</script>